package com.hkzhao.reportingsystem.service.impl;

import com.github.pagehelper.PageHelper;
import com.hkzhao.reportingsystem.common.api.CommonResult;
import com.hkzhao.reportingsystem.common.utils.TranslateToToken;
import com.hkzhao.reportingsystem.dao.AddtionDiagnosisRepository;
import com.hkzhao.reportingsystem.dao.ReportSystemDao;
import com.hkzhao.reportingsystem.dao.TotalDataRepository;
import com.hkzhao.reportingsystem.mbg.mapper.*;
import com.hkzhao.reportingsystem.mbg.model.*;
import com.hkzhao.reportingsystem.service.NormalUserService;
import com.hkzhao.reportingsystem.service.RedisTmpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class NormalUserServiceImpl implements NormalUserService {
    private static final Logger LOGGER = LoggerFactory.getLogger(NormalUserServiceImpl.class);
    @Autowired(required = false)
    private UserMapper userMapper;
    @Autowired(required = false)
    private NewsMapper newsMapper;
    @Autowired(required = false)
    private CommentMapper commentMapper;
    @Autowired(required = false)
    private ReportSystemDao reportSystemDao;
    @Autowired
    private RedisTmpService redisTmpService;
    @Autowired(required = false)
    private ProvinceMapper provinceMapper;
    @Autowired(required = false)
    private CityMapper cityMapper;
    @Value("${redis.key.add.prefix}")
    private String add_stars_prefix;
    @Autowired
    private AddtionDiagnosisRepository repository;
    @Autowired
    private TotalDataRepository totalDataRepository;
    @Override
    public boolean userlogin(String openid, String username) {
        if(getUserFromToken(openid)!=null)
            return true;
        User user = new User();
        user.setToken(openid);
        user.setUsername(username);
        userMapper.insert(user);
        return true;
    }

    @Override
    public User getUserFromToken(String openid) {
        User user = userMapper.selectByPrimaryKey(openid);
        return user;
    }

    @Override
    public List<News> getListNews(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return newsMapper.selectByExampleWithBLOBs(new NewsExample());
    }

    @Override
    public List<Comment> getCommentListByNews(int pageNum, int pageSize, String news_id) {
        CommentExample c = new CommentExample();
        c.createCriteria().andNewsIdEqualTo(news_id);
        PageHelper.startPage(pageNum,pageSize);
        return commentMapper.selectByExampleWithBLOBs(c);
    }

    @Override
    public List<Comment> getCommentListByUser(int pageNum, int pageSize, String user_token) {

         CommentExample c = new CommentExample();
         c.createCriteria().andUserTokenEqualTo(user_token);
        PageHelper.startPage(pageNum,pageSize);
         return commentMapper.selectByExampleWithBLOBs(c);
    }

    @Override
    public CommonResult deleteCommentByUser(String comment_id, String user_token) {
        if(user_token.length()==0)
            return CommonResult.failed("usertoken为空");
        Comment c = commentMapper.selectByPrimaryKey(comment_id);
        if(c.getUserToken().equals(user_token))
        {
            commentMapper.deleteByPrimaryKey(comment_id);
            return CommonResult.success(c.getCommentId(),"成功删除此条评论");
        }
        return CommonResult.failed("user_token没有此条评论");
    }

    @Override
    public CommonResult addCommentByUserAndNew(String user_token, String news_id,String text) {
        if(user_token.length()==0)
            return CommonResult.failed("usertoken为空");
        Comment comment = new Comment();
        String s = TranslateToToken.GetGUID();
        comment.setCommentId(s);comment.setStars(0);comment.setText(text);comment.setTimestamp(new Date());
        comment.setUserToken(user_token);comment.setNewsId(news_id);
        commentMapper.insert(comment);
        return CommonResult.success(s,"成功插入此条评论");
    }

    @Override
    public CommonResult addStarsToComment(String[] comment_id, String user_token) {
        if(user_token.length()==0)
            return CommonResult.failed("usertoken为空");
        for (int i = 0; i < comment_id.length; i++) {
            redisTmpService.sAdd(add_stars_prefix+comment_id[i],user_token);
        }
       return CommonResult.success(user_token,"用户成功点赞");
    }

    @Override
    public CommonResult cancelStarsToComment(String[] comment_id, String user_token) {
        if(user_token.length()==0)
            return CommonResult.failed("usertoken为空");
        for (int i = 0; i < comment_id.length; i++) {
            Set<Object> user = redisTmpService.sMembers(add_stars_prefix+comment_id[i]);
            for (Object o :user)
            {
                String oo  = (String) o;
                if(oo.equals(user_token))
                    redisTmpService.sRemove(add_stars_prefix+comment_id[i],o);
            }
        }
        return CommonResult.success(user_token, "取消点赞成功");
    }

    @Override
    public void updateStarsNumInMysql() {
        Set<String> set = redisTmpService.getKeysByRegular(add_stars_prefix+"*");
        for(String comment:set)
        {
            Set<Object> count = redisTmpService.sMembers(comment);
            int stars = count.size();
            String comm = comment.replaceFirst(add_stars_prefix,"");
            reportSystemDao.updateStarsByCommentId(comm,stars);
        }
        LOGGER.info("成功更新点赞数");
    }

    @Override
    public CommonResult getOrderByLevel() {
        return CommonResult.success(reportSystemDao.orderByLevel(),"根据危重等级的一个json返回");
    }

    @Override
    public CommonResult getOrderByGender() {
        return CommonResult.success(reportSystemDao.orderByGender(),"返回性别人数json");
    }

    @Override
    public CommonResult getOrderByAge() {
        int i =0,j=0,k=0,l=0;
        List<Integer> list = reportSystemDao.orderByAge();
        for(int z:list)
        {
            if(z<=18) i++;
            else if(z<=45) j++;
            else if(z<=60) k++;
            else l++;
        }
        Map<String,Integer> map = new HashMap<>();
        map.put("18及以下",i);map.put("19-45",j);
        map.put("46-60",k);map.put("61-",l);
        return CommonResult.success(map,"年龄段人数确诊");
    }

    @Override
    public CommonResult getProvinceData() {
        ProvinceExample p = new ProvinceExample();
        return CommonResult.success(provinceMapper.selectByExample(p),"所有省份的数据，建议前端跟数据库一样排序");
    }

    @Override
    public CommonResult getCityData() {
        return CommonResult.success(reportSystemDao.getOrderByCity(),"城市信息");
    }

    @Override
    public CommonResult getAddtionEveryDay() {
        return CommonResult.success(repository.findAll(),"每一天的数据都在这里了");
    }

    @Override
    public CommonResult getTotalEveryDay() {
        return CommonResult.success(totalDataRepository.findAll(),"当天前一天的所有数据的全部数据");
    }
}
